import React from 'react';
import { Linking, Image, ScrollView, StyleSheet, Text, View, TouchableOpacity, TextInput } from 'react-native';

import DelayTouchableOpacity from '../Component/DelayTouchableOpacity'

import Constant from '../Constant/Constant'
import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import StorageUtils from '../Utils/StorageUtils'

export default class NavigatorContact extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            searchText: '',
            isShowCancelDelete: false,
            datas: {},
        };
    }

    componentDidMount()
    {
        this.getContacts('');
    }

    getContacts(searchText)
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    if (searchText != '')
                    {
                        HttpUtils.getJson(Constant.contacts + '?realName=' + searchText, session, function (resultcode, data)
                        {
                            that.setState({
                                datas: data
                            })
                        }, function (resultcode, reason)
                        {
                            ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                        });
                    } else
                    {
                        HttpUtils.getJson(Constant.contacts, session, function (resultcode, data)
                        {
                            that.setState({
                                datas: data
                            })
                        }, function (resultcode, reason)
                        {
                            ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                        });
                    }

                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    searchChange(text)
    {
        if (text.length > 0)
        {
            this.setState({
                isShowCancelDelete: true,
                searchText: text
            })
        } else
        {
            this.setState({
                isShowCancelDelete: false,
                searchText: text
            })
            this.getContacts('');
        }
    }

    searchEnd()
    {
        this.getContacts(this.state.searchText);
    }

    cancelSearch()
    {
        this.setState({
            searchText: '',
            isShowCancelDelete: false
        })
        this.getContacts('');
    }

    callPhone(phone)
    {
        let url = 'tel: ' + phone;
        Linking.canOpenURL(url).then(supported =>
        {
            if (!supported)
            {
                console.log('Can\'t handle url: ' + url);
            } else
            {
                return Linking.openURL(url);
            }
        }).catch(err => console.error('An error occurred', err));
    }

    renderSubContacts(tip, arrays)
    {
        if (arrays != null)
        {
            let allData = [];
            allData.push(
                <View key={tip} style={{justifyContent: 'center'}}>
                    <View style={{paddingLeft: 16, paddingRight: 16, paddingTop: 12, paddingBottom: 12, flexDirection: 'row', alignItems: 'center'}}>
                        <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{tip}</Text>
                        </View>
                    </View>
                    <View style={{marginLeft: 12, backgroundColor: ColorUtils.line, height: 1}}/>
                </View>
            );
            for (let i = 0; i < arrays.length; i++)
            {
                let item = arrays[i];
                allData.push(
                    <TouchableOpacity key={item.id} activeOpacity={0.8} onPress={() => this.callPhone(item.phone)} style={{justifyContent: 'center'}}>
                        <View style={{paddingLeft: 16, paddingRight: 16, paddingTop: 12, paddingBottom: 12, flexDirection: 'row', alignItems: 'center'}}>
                            <Image source={require("../img/user_head.png")} style={{width: 44, height: 44}}/>
                            <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                                <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.realName}</Text>
                                <Text numberOfLines={1} style={{marginTop: 4, fontSize: ScreenUtils.Font_12, color: ColorUtils.light_gray}}>{item.deptName}</Text>
                            </View>
                        </View>
                        <View style={{marginLeft: 24, backgroundColor: ColorUtils.line, height: 1}}/>
                    </TouchableOpacity>
                );
            }
            return allData;
        }
    }

    renderContacts()
    {
        let allData = [];
        allData.push(this.renderSubContacts('A', this.state.datas.a));
        allData.push(this.renderSubContacts('B', this.state.datas.b));
        allData.push(this.renderSubContacts('C', this.state.datas.c));
        allData.push(this.renderSubContacts('D', this.state.datas.d));
        allData.push(this.renderSubContacts('E', this.state.datas.e));
        allData.push(this.renderSubContacts('F', this.state.datas.f));
        allData.push(this.renderSubContacts('G', this.state.datas.g));
        allData.push(this.renderSubContacts('H', this.state.datas.h));
        allData.push(this.renderSubContacts('I', this.state.datas.i));
        allData.push(this.renderSubContacts('J', this.state.datas.j));
        allData.push(this.renderSubContacts('K', this.state.datas.k));
        allData.push(this.renderSubContacts('L', this.state.datas.l));
        allData.push(this.renderSubContacts('M', this.state.datas.m));
        allData.push(this.renderSubContacts('N', this.state.datas.n));
        allData.push(this.renderSubContacts('O', this.state.datas.o));
        allData.push(this.renderSubContacts('P', this.state.datas.p));
        allData.push(this.renderSubContacts('Q', this.state.datas.q));
        allData.push(this.renderSubContacts('R', this.state.datas.r));
        allData.push(this.renderSubContacts('S', this.state.datas.s));
        allData.push(this.renderSubContacts('T', this.state.datas.t));
        allData.push(this.renderSubContacts('U', this.state.datas.u));
        allData.push(this.renderSubContacts('V', this.state.datas.v));
        allData.push(this.renderSubContacts('W', this.state.datas.w));
        allData.push(this.renderSubContacts('X', this.state.datas.x));
        allData.push(this.renderSubContacts('Y', this.state.datas.y));
        allData.push(this.renderSubContacts('Z', this.state.datas.z));
        return (
            allData
        )

    }

    render()
    {
        return (
            <ScrollView style={styles.container}>
                <View style={{margin: 32, marginTop: 16, marginBottom: 16, paddingLeft: 16, paddingRight: 16, backgroundColor: '#DDDDDD', borderRadius: 32, flexDirection: 'row', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} source={require('../img/search_icon.png')} style={{width: 20, height: 20}}/>
                    <TextInput value={this.state.searchText} underlineColorAndroid='transparent' keyboardType='default' maxLength={30} placeholder='请输入搜索姓名' onChangeText={(text) => this.searchChange(text)} onSubmitEditing={() => this.searchEnd()}
                               multiline={false} style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, flex: 1, height: 40, color: ColorUtils.black}}/>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.cancelSearch()}>
                        <Image resizeMode={Image.resizeMode.stretch} source={require('../img/cancel_search.png')} style={{width: 22, height: 22, display: this.state.isShowCancelDelete ? 'flex' : 'none',}}/>
                    </TouchableOpacity>
                </View>

                <View style={{borderRadius: 12, marginLeft: 16, marginRight: 16, backgroundColor: ColorUtils.white}}>
                    {this.renderContacts()}
                </View>
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.bgColor,
    },
});
